<template>
  {{ mValue }}
  </template>
  <script setup lang="ts">
  import { PropType, computed, onMounted, watch } from 'vue';
  import { MTableColumnType } from '../../Table/types';
  import { requestData } from '../../Form';
  import { useSelectStore } from '/@/store/modules/select';
  import { DefaultOptionType } from 'ant-design-vue/lib/cascader';
  const selectStore = useSelectStore();
  const props = defineProps({
    data: {
      // 当前行数据
      type: Object
    },
    column: {
      // 列定义数据
      type: Object as PropType<MTableColumnType>
    }
  })
  /**
   * 获取缓存key前辍
   */
  const getCacheKeyPrefix = () =>{
    let cacheKeyPrefix = props.column?.componentProps?.cacheKeyPrefix
    if(!cacheKeyPrefix) {
      // Cascader_columnName
      cacheKeyPrefix = props.column?.component + "_" + (props.column?.key || props.column?.dataIndex)
    }
    return cacheKeyPrefix;
  }
  /**
   * 获取节点
   * @param id 节点id,对应value
   * @param treeData 树型数据
   */
  const getNodeData = (id: string | number | null,treeData:Array<DefaultOptionType> | undefined):DefaultOptionType | undefined =>{
    let res: DefaultOptionType | undefined;
    if(treeData) {
      for(var i=0;i<treeData.length;i++) {
        const item = treeData[i]
        if(item.value == id) {
          // 先父子查询
          res = item;
          break
        } else {
          // 再从子中查询
          const childItem = getNodeData(id,item.children)
          if(childItem) {
            res = childItem;
            break;
          }
        }
      }
    }
    return res
  }
  const mValue = computed(()=>{
    let v = props.data?.text
    if(!v) return v;
    if(typeof v == 'string') {
      v = v.split(',')
    }
    const key = getCacheKeyPrefix() + "_" + v;
    const treeData = selectStore.getSelectData(key)
    const nodeDatas:Array<DefaultOptionType> = []
    v?.forEach((id: string | number | null)=>{
      const nodeData = getNodeData(id,treeData)
      if(nodeData) {
        nodeDatas.push(nodeData)
      } else {
        nodeDatas.push({
          label: id,
          value: id
        })
      }
    })
    return nodeDatas.map((item: any)=>item.label).join('/')
  })
  // 设置值
  const setValue = () =>{
    const api = props.column?.componentProps?.api
    if(api) {
      const text = props.data?.text
      if(text){
        const key = getCacheKeyPrefix() + "_" + text
        selectStore.requestData(key,api,{
         ...props.column?.componentProps?.params
        },requestData)
      }
    }
  }
  watch(()=>props.data?.text,()=>{
    setValue()
  })
  onMounted(()=>{
    setValue()
  })
  </script>
  <style lang="less" scoped>
  
  </style>